package dbservice

import (
	"fmt"
	"time"

	"github.com/buguang01/util"
)

const (
	ScenePrefix   = "Scene:"
	SceneExSecond = 60
)

var (
	ErrorExpire = fmt.Errorf("Redis expire fail.")
)

// 用与设置对应配置服务器的ID
func GetSceneKey(sid uint64) string {
	return fmt.Sprint(ScenePrefix, sid)
}

/*
Scene服务器注册信息
Scene会自己关心自己的服务器类型，主要是检查load信息
*/
type SceneUtil struct {
	SID uint64 //服务器ID
	Key string //Key

}

func NewSceneUtil(sid uint64) *SceneUtil {
	result := new(SceneUtil)
	result.SID = sid
	result.Key = GetSceneKey(sid)
	return result
}

// 注册服务器信息
func (this *SceneUtil) Register() (err error) {
	c := GetEntityRedis()
	defer c.Dispose()
	_, err = c.HMSet(c.Ctx, this.Key).Result()
	return err
}

// 刷新key的时间
func (this *SceneUtil) RefreshEx() error {
	c := GetEntityRedis()
	defer c.Dispose()
	if n, err := c.Expire(c.Ctx, this.Key, SceneExSecond*time.Second).Result(); err != nil {
		return err
	} else if n {
		return nil
	} else {
		return ErrorExpire
	}
}

// 设置地图对应的人数
func (this *SceneUtil) SetMapNum(mapid uint64, num int32) (err error) {
	c := GetEntityRedis()
	defer c.Dispose()
	err = c.HMSet(c.Ctx, this.Key, mapid, num).Err()
	return err
}

// 获取服务器地图数据
func (this *SceneUtil) GetServerMap(sid uint64) (result map[string]int64, err error) {
	c := GetEntityRedis()
	defer c.Dispose()
	result, err = c.HgetallByInt64Map(GetSceneKey(sid))
	return
}

// 删除地图
func (this *SceneUtil) ClearMap(mapid uint64) (err error) {
	c := GetEntityRedis()
	defer c.Dispose()
	err = c.HDel(c.Ctx, this.Key, util.NewStringAny(mapid).String()).Err()
	return err
}
